package com.liu.service.impl;

import com.github.pagehelper.PageHelper;
import com.liu.dao.BookInfoMapper;
import com.liu.dao.BookMapper;
import com.liu.model.Book;
import com.liu.model.BookInfo;
import com.liu.service.BookService;
import com.liu.tools.MyConstant;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by liu on 2018/3/26.
 */
@Service(value = "bookService")
public class BookServiceImpl implements BookService{

    @Resource
    BookMapper bookDao;

    @Resource
    BookInfoMapper bookInfoDao;


    @Override
    public Boolean add(Book book) {
        book.setCreateTime(new Date());
        book.setUpdateTime(new Date());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String num = "book"+sdf.format(new Date());
        book.setNum(num);
        book.setBorrowStatus(MyConstant.BOOKINFO_RETURN);
        Boolean flag = bookDao.save(book);

        BookInfo bookInfo = bookInfoDao.findById(book.getBookInfoId());
        bookInfo.setUpdateTime(new Date());
        bookInfo.setStockNum(bookInfo.getStockNum() + 1);
        bookInfoDao.edit(bookInfo);
        return flag;
    }

    @Override
    public Boolean edit(Book book) {
        Boolean flag = bookDao.edit(book);
        return flag;
    }

    @Override
    public Boolean deleteById(String id) {
        Book book = bookDao.findById(id);
        BookInfo bookInfo = bookInfoDao.findById(book.getBookInfoId());
        bookInfo.setUpdateTime(new Date());
        if (bookInfo.getStockNum() > 0) {
            bookInfo.setStockNum(bookInfo.getStockNum() - 1);
        }
        bookInfoDao.edit(bookInfo);
        Boolean flag = bookDao.deleteById(id);
        return flag;
    }

    @Override
    public Book findById(String id) {
        return bookDao.findById(id);
    }

    /*
   * 这个方法中用到了我们开头配置依赖的分页插件pagehelper
   * 很简单，只需要在service层传入参数，然后将参数传递给一个插件的一个静态方法即可；
   * pageNum 开始页数
   * pageSize 每页显示的数据条数
   * */
    @Override
    public List<Book> findAll(int pageNum, int pageSize, Map<String, Object> queryMap) {
        //将参数传给这个方法就可以实现物理分页了，非常简单。
        PageHelper.startPage(pageNum, pageSize);
        List<Book> list = bookDao.findAll(queryMap);

        return list;
    }
}
